package jodis.conn.impl;


import jodis.conn.inter.IConnection;

import java.io.IOException;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

public class JoConnection implements IConnection {

    private Socket conn;
    private SocketChannel channel;
    private int selectedDB;
    private int role;

    public static final int NORMAL_CLI = 0;
    public static final int REPLICATION_CLI = 1;
    public static final int AOF_CLI = 2;

    public static JoConnection fakeConn(int dbIndex) {
        return new JoConnection(null, AOF_CLI, dbIndex);
    }

    public JoConnection(Socket conn) {
        this.conn = conn;
        this.role = NORMAL_CLI;
        // 默认用 0 号数据库
        this.selectedDB = 0;
    }

    public JoConnection(SocketChannel socketChannel) {
        channel = socketChannel;
        this.role = NORMAL_CLI;
        // 默认用 0 号数据库
        this.selectedDB = 0;

    }

    public JoConnection(Socket conn, int role) {
        this.conn = conn;
        this.role = role;
        // 默认用 0 号数据库
        this.selectedDB = 0;
    }

    public JoConnection(Socket conn, int role, int dbIndex) {
        this.conn = conn;
        this.role = role;
        // 默认用 0 号数据库
        this.selectedDB = dbIndex;
    }

    @Override
    public void writeWithNIO(byte[] bs) throws IOException {
        channel.write(ByteBuffer.wrap(bs));
    }

    @Override
    public void write(byte[] bs) throws IOException {
        conn.getOutputStream().write(bs);
        conn.getOutputStream().flush();
    }

    @Override
    public int getDBIndex() {
        return selectedDB;
    }
    @Override
    public void selectDB(int index) {
        selectedDB = index;
    }

    @Override
    public int getRole() {
        return role;
    }

    @Override
    public void setRole(int role) {
        this.role = role;
    }
}
